<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class JsonResponses
{
    const ACCESS_CONTROL_ALLOW = [
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Headers' => "Content-Type,Access-Token,Authorization",
    ];

    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        // 获取状态
        $status = intval($response->getStatusCode());
        if ($status !== 200 && $status !== 201) {
            $methodName = "handle$status";

            return method_exists($this, $methodName) ? call_user_func([$this, $methodName],
                $response) : $this->handleError($response);
        } else {
            $returnData = json_decode($response->getContent(), true) ?? $response->content();

            if (is_null($returnData)) {
                $returnData = [];
            }

            $result = [
                'code' => $returnData['code'] ?? 200000,
                'success' => true,
                'message' => '请求成功',
                'data' => $returnData,
            ];
            
            // 在debug模式下添加SQL查询日志
            if (config('app.debug')) {
                $result['sql_queries'] = \Illuminate\Support\Facades\DB::getQueryLog();
            }

            if (isset($returnData['error_message'])) {
                $result['success'] = false;
                $result['message'] = $returnData['error_message'];
                $result['data'] = $returnData['data'] ?? [];
            } else {
                if (isset($returnData['success_message'])) {
                    $result['message'] = $returnData['success_message'];
                    $result['data'] = $returnData['data'];
                }
            }
        }

        $headers = array_merge(self::ACCESS_CONTROL_ALLOW, [
            'Server-Time' => date('Y-m-d H:i:s'),
        ]);

        return response()->json($result, $status)->withHeaders($headers);
    }

    /**
     * Name: 处理错误
     * User: Lark
     * Data: 2022/7/15
     * Time: 13:44
     *
     * @param $response
     * @return Response
     */
    protected function handleError($response): Response
    {
        $exceptionHandle = $response->exception;
        $exception = [
            'file' => $exceptionHandle->getFile(),
            'line' => $exceptionHandle->getLine(),
            'error_message' => $exceptionHandle->getMessage(),
        ];
        $message = $exceptionHandle->getMessage();
        $returnData = ['success' => false, 'message' => $message];
        if (config('app.debug')) {
            $returnData ['exception'] = $exception;
        }

        return response($returnData, $response->getStatusCode());
    }

    /**
     * Name: 401 状态提示
     * User: Lark
     * Data: 2022/7/15
     * Time: 13:45
     *
     * @param JsonResponse $jsonResponse
     * @return JsonResponse
     */
    protected function handle401(JsonResponse $jsonResponse): JsonResponse
    {
        $data = $jsonResponse->getData();
        $data->success = false;
        $data->code = '400001';
        $data->message = isset($data->message) && $data->message != 'Unauthenticated.' ? $data->message : '未授权, 请授权登录';

        return response()->json($data, '401');
    }

    /**
     * Name: 404 状态提示
     * User: Lark
     * Data: 2022/7/15
     * Time: 13:45
     *
     * @param JsonResponse $response
     * @return JsonResponse
     */
    protected function handle404(JsonResponse $response): JsonResponse
    {
        $data = $response->getData();
        $data->success = false;
        $data->code = '400004';
        $data->message = isset($data->message) && $data->message != 'Not Found.' ? $data->message : '请求的内容不存在';

        return response()->json($data, '404');
    }

    /**
     * Name: 422 状态提示
     * User: Lark
     * Data: 2022/7/15
     * Time: 13:46
     *
     * @param JsonResponse $jsonResponse
     * @return JsonResponse
     */
    protected function handle422(JsonResponse $jsonResponse): JsonResponse
    {
        $data = $jsonResponse->getData();
        $data->success = false;
        $data->code = '400022';

        return response()->json($data, 422);
    }

    /**
     * Name: 429 状态提示
     * User: Lark
     * Data: 2022/7/15
     * Time: 13:46
     *
     * @return JsonResponse
     */
    protected function handle429(): JsonResponse
    {
        $success = false;
        $message = '请求过于频繁，请稍后重试。';
        $code = '400029';

        return response()->json(compact('success', 'message', 'code'), '429');
    }

    /**
     * Name: 500 状态提示
     * User: Lark
     * Data: 2022/7/15
     * Time: 13:46
     *
     * @return JsonResponse
     */
    protected function handle500(): JsonResponse
    {
        $success = false;
        $message = '服务繁忙，请稍后重试。';
        $code = '500000';

        return response()->json(compact('success', 'message', 'code'), '500');
    }
}
